<!--  -->
<template>
  <div class="workScheduling-pack">
    <ele-form-search
      :formConfig="formConfig"
      :initForm="initForm"
      @handleSearch="handleSearch"
      @handleReset="handleReset"
      ref="eleFormSearch"
    ></ele-form-search>
    <div class="tit">
      <div class="title-pack">
        <div class="title">
          <div class="icon"></div>
          <div class="text">
            {{ $i18n.t("abnormalProcessAnalysis.warnTotal") }}
          </div>
        </div>
      </div>
      <div>
        <el-button
          type="primary"
          icon="el-icon-download"
          @click="exportExcl()"
          >{{ $i18n.t("common.export") }}</el-button
        >
      </div>
    </div>
    <el-tabs type="border-card" @tab-click="tabClick">
      <el-tab-pane>
        <span slot="label">
          <p>
            <i class="el-icon-date"></i>
            {{ $i18n.t("abnormalProcessAnalysis.picture") }}
          </p>
        </span>
        <div style="width: 100%; height: calc(100vh - 300px);">
          <ECharts
            ref="vCharts"
            v-if="chartData.length && echartData"
            :option="options"
            class="bg-white"
            style="width: 100%; height: calc(100vh - 300px);"
          />
          <el-empty v-else> </el-empty>
        </div>
      </el-tab-pane>
      <el-tab-pane>
        <span slot="label"
          ><i class="el-icon-document"></i>
          {{ $i18n.t("abnormalProcessAnalysis.table") }}</span
        >
        <div>
          <el-table
            :data="tableData"
            border
            height="calc(100vh - 300px)"
            :summary-method="getSummaries"
            show-summary
            style="width: 100%; margin-top: 20px;"
          >
            <el-table-column
              type="index"
              :label="$i18n.t('common.order')"
              width="70"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="productProcessCode"
              :label="$i18n.t('abnormalProcessAnalysis.processCode')"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="productProcessName"
              :label="$i18n.t('abnormalProcessAnalysis.processName')"
              align="center"    show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="prodCode"
              :label="$i18n.t('abnormalProcessAnalysis.productCode')"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="prodName"
              :label="$i18n.t('abnormalProcessAnalysis.productName')"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="quantity"
              :label="$i18n.t('abnormalProcessAnalysis.warningTotal')"
              align="center" 
            >
            </el-table-column>
            <el-table-column
              prop="repairQuantity"
              :label="$i18n.t('abnormalProcessAnalysis.repairQuantity')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="dropQuantity"
              :label="$i18n.t('abnormalProcessAnalysis.dropQuantity')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="exceptionRate"
              :label="$i18n.t('abnormalProcessAnalysis.exceptionRate')"
              align="center"
            >
              <template slot="header" slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="
                    $i18n.t('abnormalProcessAnalysis.processWarnTotalAndAll')
                  "
                  placement="top"
                >
                  <div>
                    {{ $i18n.t("abnormalProcessAnalysis.exceptionRate") }}
                    <i class="el-icon-question"></i>
                  </div>
                </el-tooltip>
              </template>

              <template slot-scope="scope">
                {{ scope.row.exceptionRate || 0 }} %
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
//例如：import 《组件名称》 from '《组件路径》';
import eleFormSearch from "@/components/ele-form-search/index";
import "echarts";
import { exportExcel } from "@/utils/judge.js";
import ECharts from "vue-echarts";
import { getLineCodeListNew } from "@/api/order/mesProdOrder";
import {
  getProcessExceptionView,
  getProcessExceptionList,
  exportUrl,
} from "@/api/report/abnormalProcessAnalysis.js";
import { searchArrKey } from "@/mixins/searchArrKey";
import { getDict } from "@/api/common";
export default {
  name: "abnormalProcessAnalysis",
  //import引入的组件需要注入到对象中才能使用
  components: { eleFormSearch, ECharts },
  mixins: [searchArrKey],
  data() {
    //这里存放数据
    const self = this;
    var choiceDate = null;
    return {
      options: {},
      formConfig: {
        inline: true,
        formDesc: {
          defectiveStatus: {
            label: $i18n.t("abnormalProcessAnalysis.state"),
            type: "select",
            prop: {
              value: "value",
              text: "description",
            },
            options: async (data) => {
              const list = await getDict("defective_status");
              return list.data.result;
            },
          },
          deliveryDate: {
            type: "daterange",
            label: $i18n.t("abnormalProcessAnalysis.daterange"),
            attrs: {
              valueFormat: "yyyy-MM-dd",
              searchArrKey: ["beginDate", "endDate"],
              clearable: false,
              pickerOptions: {
                onPick: ({ maxDate, minDate }) => {
                  // 把选择的第一个日期赋值给一个变量。
                  choiceDate = minDate.getTime();

                  // 如何你选择了两个日期了，就把那个变量置空
                  if (maxDate) choiceDate = "";
                },
                disabledDate: (time) => {
                  // 如何选择了一个日期
                  if (choiceDate) {
                    // 7天的时间戳
                    const one = 365 * 24 * 3600 * 1000;
                    // 当前日期 - one = 7天之前
                    const minTime = choiceDate - one;
                    // 当前日期 + one = 7天之后
                    const maxTime = choiceDate + one;
                    return time.getTime() < minTime || time.getTime() > maxTime;
                  } else {
                    // 如果没有选择日期，就要限制不能选择今天及以后
                    // return time.getTime() > Date.now();
                  }
                },
              },
            },
          },
          workshopCode: {
            type: "select",
            label: $i18n.t("abnormalProcessAnalysis.workshop"),
            prop: {
              value: "modelingCode",
              text: "modelingName",
            },
            options: async (data) => {
              const params = {
                modelingCode: self.$store.getters.factoryCode,
                level: 4,
                modelingType: "0",
              };
              const list = await getLineCodeListNew(params);
              return list.data.result;
            },
          },
          productProcessName: {
            label: $i18n.t("abnormalProcessAnalysis.processName"),
            type: "input",
          },
          prodName: {
            type: "input",
            label: $i18n.t("abnormalProcessAnalysis.productName"),
          },
        },
      },
      initForm: {},
      tableData: [],
      rightList: [[], [], [], []],
      queryData: {},
      chartData: [],
      echartData: false,
      loading: false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    exportExcl() {
      exportExcel(exportUrl, this.getSearchParams());
    },
    tabClick(data) {
      if (data.index == "0") {
        setTimeout(() => {
          this.$refs.vCharts.resize();
        }, 0);
      }
    },
    // 表格合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = $i18n.t("abnormalProcessAnalysis.total");
          return;
        }
        if ( ![5,6,7].includes(index) ) {
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
    // 当月第一天最后一天
    getMonthStartAndEnd(dateString) {
      const date = dateString ? new Date(dateString) : new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      // const firstDay = new Date(year, month - 1, 1);
      const lastDay = new Date(year, month, 0);
      const formattedFirstDay = `${year}-${month
        .toString()
        .padStart(2, "0")}-01`;
      const formattedLastDay = `${year}-${month
        .toString()
        .padStart(2, "0")}-${lastDay.getDate()}`;
      return { firstDay: formattedFirstDay, lastDay: formattedLastDay };
    },

    // 初始化图表
    initOptions(xData, source, names) {
      const colors = ["#F26A61", "#F5BC5A", "#68A2F8", "#00BFA5"];
      this.options = {
        tooltip: {
          show: true,
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter(params) {
            var res = `${params[0].name} <br/>`;
            for (const item of params) {
              if (item.value !== 0) {
                res += `<span style="background: ${item.color}; height:10px; width: 10px; border-radius: 50%;display: inline-block;margin-right:10px;"></span> ${item.seriesName} ：${item.value}<br/>`;
              }
            }
            return res;
          },
        },
        legend: {
          data: names,
          left: "1%",
        },
        grid: {
          left: "2%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
        },
        yAxis: {
          type: "category",
          data: xData,
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
          },
          axisLabel: {
            show: true,
            color: "#333",
            formatter: function (value) {
              // 自定义换行逻辑
              return (
                value.slice(0, 4) +
                "\n" +
                value.slice(4, 8) +
                "\n" +
                value.slice(8, 20)
              );
            },
          },
        },
        series: [],
      };
      this.options.series = Object.keys(source).map((v, index) => {
        return {
          name: names[index],
          type: "bar",
          stack: "total",
          label: {
            show: true,
            color: "#333333",
            formatter(value) {
              return value.data || "";
            },
          },
          emphasis: {
            focus: "series",
          },
          data: source[v],
        };
      });
    },
    // 获取包装图标数据
    getChartData(data) {
      this.loading = true;
      this.echartData = false;
      getProcessExceptionView(data)
        .then((res) => {
          this.chartData = res.data.result.reverse();
          const xData = [];
          const namesMap = {};
          const names = [];
          res.data.result.forEach((v) => {
            xData.push(v.prodName);
            v.processList.forEach((o) => {
              namesMap[o.productProcessName] = 1;
            });
          });
          Object.keys(namesMap).forEach((v) => {
            names.push(v);
          });
          const source = {};
          names.forEach((v) => {
            source[v] = [];
          });
          xData.map((v) => {
            const item = res.data.result.find((o) => o.prodName === v);
            Object.keys(source).map((v) => {
              const o = item.processList.find(
                (t) => t.productProcessName === v
              );
              source[v].push(o ? o.quantity : 0);
            });
          });
          console.log(7777,source)
          this.initOptions(xData, source, names);
        })
        .finally(() => {
          this.loading = false;
          this.echartData = true;
        });
    },
    // 获取table数据
    async getTableData() {
      try {
        this.loading = true;
        let res = await getProcessExceptionList(this.getSearchParams());

        this.tableData = res.data.result;
      } finally {
        this.loading = false;
      }
    },
    // 获取表单内容
    getSearchParams() {
      let formData = this.$refs.eleFormSearch.formData || {};
      formData = this.getArrtoMap(formData);
      return formData;
    },
    async getWorkSchedule() {
      let data = this.getSearchParams();
      this.getChartData(data);
    },
    // 搜索
    handleSearch() {
      this.init();
    },
    // 重置
    handleReset() {
      this.setDate();
      this.init();
    },
    //设置默认七天
    setDate() {
      let { firstDay, lastDay } = this.getMonthStartAndEnd();
      this.$set(this.initForm, "deliveryDate", [firstDay, lastDay]);
    },
    init() {
      this.$nextTick(() => {
        this.getWorkSchedule();
        this.getTableData();
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.setDate();
    this.init();
  },
  activated() {
    this.tabClick({ index: "0" });
  },
};
</script>
<style scoped lang="scss">
.workScheduling-pack {
  width: 100%;
  height: 100%;
  /deep/.el-table {
    margin-top: 0px !important;
  }
  .tit {
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: space-between;
    .title {
      display: flex;
      align-items: center;

      .icon {
        width: 4px;
        height: 16px;
        background-color: #00bfa5;
        margin-right: 10px;
      }
      .text {
        font-weight: 800;
      }
    }
  }
  .right {
    width: 100%;
    overflow: auto;
    .header {
    }
    .th {
      width: 300px;
      height: 50px;
      text-align: center;
      background: #ebf0f5;
      margin-right: 10px;
      flex-shrink: 0;
      box-sizing: border-box;
      font-size: 14px;
      font-weight: 700;
    }
    .tables {
      width: 1240px;
      min-height: 200px;
      max-height: 450px;
      overflow-y: auto;
      overflow-x: hidden;
      text-align: center;
    }
    .tabody {
      margin-right: 10px;
      width: 300px;
      .td {
        margin-top: 10px;
        width: 300px;
        .card {
          width: 300px;
          cursor: pointer;
          // height: 130px;
          .card-box {
            display: flex;
            flex-direction: column;
            justify-content: center;
            .count {
              color: #595858;
            }
            & > p {
              font-size: 14px;
              text-align: left;
            }
            .icon {
              color: #bcbec2;
            }
          }
        }
        .notice {
          border-color: #e7a11a;
          .order-title__msg {
            color: #e7a11a;
          }
        }
        .overtime {
          border-color: #ff4656;

          .order-title__msg {
            color: #ff4656;
          }
        }
      }
    }

    .border1 {
      border-bottom: 8px solid #64b5ea;
    }
    .border2 {
      border-bottom: 8px solid #f4bb5b;
    }
    .border3 {
      border-bottom: 8px solid #3d82ea;
    }
    .border4 {
      border-bottom: 8px solid #00bfa5;
    }
    .border5 {
      border-bottom: 8px solid #93b0cb;
    }
  }

  .mark-item:before {
    content: " ";
    position: absolute;
    left: 6px;
    top: 6px;
    width: 16px;
    height: 12px;
    border: 2px solid #ccc;
    border-radius: 6px;
    background-color: #eee;
  }
  .example {
    // position: absolute;
    float: right;
  }
  .shengchanzhong:before {
    background-color: rgba(177, 207, 250, 0.39);
    border-color: #3d82ea;
  }
  .wancheng:before {
    background-color: #18c9274f;
    border-color: #18c927;
  }
  .daixiafa:before {
    background-color: rgba(239, 226, 247, 0.5);
    border-color: #c682ee;
  }

  .daishengchan:before {
    background-color: rgba(222, 242, 255, 0.5);
    border-color: #64b5ea;
  }
  .daishengchan,
  .daixiafa,
  .shengchanzhong {
    .mark-check {
      display: block;
    }
  }
  /deep/.el-card__body {
    padding: 14px !important;
  }
  .flex {
    display: flex;
  }

  .flex-j-sb {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .flex-a-c {
    display: flex;
    align-items: center;
  }

  .flex-all-c {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .p-b-5 {
    padding-bottom: 5px;
  }
  .font-w {
    font-weight: 600;
  }
  .m-auto {
    margin: 0 auto;
  }
}
</style>
